// / 多个 VBO，VAO，多个着色器 例子
package main

import (
	"github.com/go-gl/gl/v4.5-core/gl"
	"github.com/go-gl/glfw/v3.3/glfw"
)

const (
	width  = 600
	height = 400
)

func processInputKey(win *glfw.Window) {
	win.SetKeyCallback(func(w *glfw.Window, key glfw.Key, scancode int, action glfw.Action, mods glfw.ModifierKey) {
		println("key name:", glfw.GetKeyName(key, scancode))
		if key == glfw.KeyEscape && action == glfw.Release {
			win.SetShouldClose(true)
		}
	})
}

func glfwInit() (window *glfw.Window) {
	if err := glfw.Init(); err != nil {
		panic("glfw init fail:" + err.Error())
	}
	glfw.WindowHint(glfw.Resizable, glfw.True)
	glfw.WindowHint(glfw.ContextVersionMajor, 4)
	glfw.WindowHint(glfw.ContextVersionMinor, 5)
	glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)

	window, err := glfw.CreateWindow(width, height, "test opengl-go", nil, nil)
	if err != nil {
		panic("glfw create window fail: " + err.Error())
	}

	window.MakeContextCurrent()
	return
}

var VertexSource1 = `
#version 450 vore
layout (location = 0) in vec3 aPos;
void main(){
	gl_Position = vec4(aPos, 1.0);
}
` + "\x00"

var triangle1 = []float32{
	// 位置           // 颜色4
	0.5, 0.75, 0.0, 1.0, 0.4, 0.4, 1.0,
	0.25, 0.25, 0.0, 0.4, 1.0, 0.4, 1.0,
	0.75, 0.25, 0.0, 0.4, 0.4, 1.0, 1.0,
}

// 第二个三角形
var triangle2 = []float32{
	-0.5, -0.75, 0.0, 1.0, 0.6, 0.6,
	-0.25, -0.25, 0.0, 0.6, 1.0, 0.6,
	-0.75, -0.25, 0.0, 0.6, 0.6, 1.0,
}

func main() {
	window := glfwInit()
	defer glfw.Terminate()

	if err := gl.Init(); err != nil {
		panic("gl init fail:" + err.Error())
	}

	var VBO1, VBO2 uint32
	// gl.GenBuffers(2, &IBOs[0]) // TODO:测试同时生成2个VBO
	gl.GenBuffers(1, &VBO1)
	gl.GenBuffers(1, &VBO2)
	// 绑定第一个vbo
	gl.BindBuffer(gl.ARRAY_BUFFER, VBO1)
	gl.BufferData(gl.ARRAY_BUFFER, 4*len(triangle1), gl.Ptr(triangle1), gl.STATIC_DRAW)
	// 绑定第二个vbo
	gl.BindBuffer(gl.ARRAY_BUFFER, VBO2)
	gl.BufferData(gl.ARRAY_BUFFER, 4*len(triangle2), gl.Ptr(triangle2), gl.STATIC_DRAW)

	// var IBO uint32
	// gl.GenBuffers(1, &IBO)
	// gl.BindBuffer(gl.ARRAY_BUFFER, IBO)
	// gl.BufferData(gl.ARRAY_BUFFER, 4*len(triangle1_index))
	var VAO1, VAO2 uint32
	gl.GenVertexArrays(1, &VAO1)
	gl.GenVertexArrays(1, &VAO2)
	gl.BindVertexArray(VAO1)
	gl.VertexAttribPointer(0, 3, gl.FLOAT, false, 7*4, nil)
	program := gl.CreateProgram()

	shader1 := gl.CreateShader(gl.VERTEX_SHADER)
	csource, free := gl.Strs(VertexSource1)
	gl.ShaderSource(shader1, 1, csource, nil)
	free()

	gl.AttachShader(program, shader1)

	gl.LinkProgram(program)

	for !window.ShouldClose() {
		processInputKey(window)

		gl.ClearColor(1.0, 0.0, 0.0, 0.5)
		gl.Clear(gl.COLOR_BUFFER_BIT)

		glfw.PollEvents()
		window.SwapBuffers()
	}

}
